package com.study.connect.handler;

import com.study.connect.message.EmpResult;
import com.study.connect.message.InvokeResultDTO;
import com.study.connect.message.RpcExceptionResult;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.List;

/**
 * byte转InvokeResult对象编码（服务端返回对象解码）
 */
@Slf4j
public class ByteToInvokeResultDecoderHandler extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        /*读取长度，然后再读取内容*/
        byte[] array = new byte[byteBuf.readableBytes()];
        try {
            byteBuf.readBytes(array);
        } finally {
            byteBuf.skipBytes(byteBuf.readableBytes());
        }
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(array);
             ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);) {
            InvokeResultDTO resultDTO = (InvokeResultDTO) objectInputStream.readObject();
            if (InvokeResultDTO.RESULT_CODE_SUCCESS.equals(resultDTO.getCode()) && null != resultDTO.getResult()) {
                list.add(resultDTO.getResult());
            } else if (InvokeResultDTO.RESULT_CODE_FAIL.equals(resultDTO.getCode()) && null != resultDTO.getRpcException()) {
                throw resultDTO.getRpcException();
            } else {
                list.add(new EmpResult());
            }
        } catch (Exception e) {
            log.error("对象流读取异常：{}", e);
            list.add(new RpcExceptionResult(e));
        }
    }
}
